import 'dart:async';
import 'dart:io';

import 'package:common/common.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:just_audio/just_audio.dart';
import 'package:permission_handler/permission_handler.dart';

// import 'package:phone_state/phone_state.dart';

import '../../../../router/qs_navigator_observer.dart';
import 'audio_download.dart';
import 'audio_player.dart';

enum CircleAudioPlayerSource {
  user, // 个人主页  => 圆形
  homeList, // 首页列表 => 圆形
  chatCard, //  聊天卡片 => 播放条 读秒
  topicList, //  问答详情回复列表 => 播放条 读秒
  userTopicList, //  个人主页问答回复列表 => 播放条 读秒
}

class CircleAudioPlayerWidget extends StatefulWidget {
  const CircleAudioPlayerWidget(
      {super.key,
      required this.source,
      required this.audioDuration,
      required this.audioUrl,
      required this.playerId,
      this.cannotPlay = false,
      this.onCannotPlay,
      this.arguments,
      this.onPointCallBack});

  /// 页面来源
  final CircleAudioPlayerSource source;

  /// 语音时长
  final int audioDuration;

  /// 音频地址
  final String audioUrl;

  /// 播放器id
  final String playerId;
  final Map<String, dynamic>? arguments;

  /// 点击播放回调事件,用于不同页面的埋点- 暂时之后问答详情
  final Function? onPointCallBack;

  /// 是否不能播放
  final bool cannotPlay;

  /// 播放器不能播放回调
  final Function? onCannotPlay;

  @override
  State<CircleAudioPlayerWidget> createState() => _CircleAudioPlayerWidgetState();
}

class _CircleAudioPlayerWidgetState extends State<CircleAudioPlayerWidget> with RouteAware, WidgetsBindingObserver {
  StreamSubscription? _phoneStateSub;

  bool isLoading = false;
  bool isPlaying = false;
  int audioPlayingDuration = 0; //  音频播放时间进度

  // 是否在当前页面
  bool isCurrentPage = true;
  String? peerId;
  String? answerId;

  /// 准备播放声音
  void preparePlayAudio({Duration? position}) {
    if (isPlaying) {
      _stopAudioPlay();
    } else {
      _startAudioPlay(path: widget.audioUrl, duration: widget.audioDuration);
    }
    widget.onPointCallBack?.call();
  }

  /// 开始播放声音
  void _startAudioPlay({required String path, required int duration}) {
    audioPlayingDuration = duration;
    try {
      isCurrentPage = true;
      AudioDownLoad.getFile(
          filePath: widget.audioUrl,
          onProgress: (progress) {},
          onNetComplete: (url) {
            isLoading = true;
            setState(() {});
          },
          onError: () {
            isLoading = false;
            setState(() {});
          },
          complete: (filePath) {
            if (isLoading == true) {
              isLoading = false;
              if (mounted) {
                setState(() {});
              }
            }
            isPlaying = true;
            if (isCurrentPage) {
              _playAudio(filePath: filePath);
            }
          });
    } catch (e) {
      logs(e.toString());
    }
  }

  void _playAudio({required String filePath}) async {
    if (isPlaying == false) {
      return;
    }
    // 处理来电话播放器停止播放的操作
    _handlePhoneCall();
    try {
      JustAudioPlayer.instance.play(id: widget.playerId, url: filePath, stopAction: onStopPlay).then((value) {});
      audioPlayerPlayCallBack();
    } catch (e) {
      logs(e);
    }
  }

  /// 停止执行播放声音动画
  void onStopPlay() {
    if (isPlaying && mounted) {
      setState(() {
        isPlaying = false;
      });
    }
  }

  /// 停止播放声音
  void _stopAudioPlay() {
    try {
      JustAudioPlayer.instance.release();
    } catch (e) {
      logs(e.toString());
    }
    // 停止执行播放声音动画
    onStopPlay();
  }

  @override
  void initState() {
    super.initState();
    peerId = widget.arguments?["peer_id"].toString() ?? '0';
    answerId = widget.arguments?["answer_id"].toString() ?? '';
    WidgetsBinding.instance.addObserver(this);
    logs('anserId = ${widget.playerId}');
    // 获取当前播放器播放进度
    getCurrentAudioPlayerPosition();
    try {
      Future.delayed(Duration.zero, () {
        if (mounted) {
          IMKitRouter.instance.routeObserver.subscribe(this, ModalRoute.of(context)!);
        }
      });
    } catch (e) {
      logs(e.toString());
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    super.didChangeAppLifecycleState(state);
    debugPrint("testxp.chat.applifecycler = $state");
    if (state == AppLifecycleState.resumed) {
    } else if (state == AppLifecycleState.paused) {
      if (isPlaying) {
        _stopAudioPlay();
        if (isPlaying && mounted) {
          setState(() {
            isPlaying = false;
          });
        }
      }
    }
  }

  /// 获取当前播放器播放进度
  void getCurrentAudioPlayerPosition() {
    JustAudioPlayer.instance.getCurrentPosition(
        onDurationChanged: (String playerId, bool playState, Duration duration) {
      // logs('----playerId = $playerId - widget.playerId= ${widget.playerId} playState =  $playerId  - ');
      if (playerId == widget.playerId) {
        if (playState) {
          var durLast = widget.audioDuration - duration.inSeconds;
          logs('getCurrentPosition =  initState $duration = seconds = ${duration.inSeconds}  durLast = $durLast');
          isPlaying = true;
          audioPlayerPlayCallBack();
        } else {
          if (mounted) {
            setState(() {
              isPlaying = false;
            });
          }
        }
      }
    });
  }

  /// 正在播放中的播放器回调参数
  void audioPlayerPlayCallBack() {
    /// 停止播放语音
    JustAudioPlayer.instance.onStopCallback = () {
      isPlaying = false;
      if (mounted) {
        setState(() {});
      }
    };

    // 播放时长回调
    JustAudioPlayer.instance.onDurationChanged = (Duration toatlDuration, Duration duration) {
      logs('just ---  onDurationChanged = duration = $duration');
      if (mounted) {
        setState(() {
          audioPlayingDuration = widget.audioDuration - duration.inSeconds;
          debugPrint(
              'just ---  onPositionChanged  toatlDuration.inSeconds = ${toatlDuration.inSeconds}  duration.inSeconds = ${duration.inSeconds} => isPlayingDuration = $audioPlayingDuration');
        });
      }
    };
    // 播放状态回调
    // 播放状态回调
    JustAudioPlayer.instance.onPlayerStateChanged = (PlayerState state) {
      debugPrint('just ---1  onPlayerStateChanged = playerState = $state');
      if (state.processingState == ProcessingState.loading) {
        isLoading = true;
        isPlaying = false;
      } else if (state.processingState == ProcessingState.ready || state.processingState == ProcessingState.buffering) {
        isLoading = false;
        isPlaying = true;
      } else if (state.processingState == ProcessingState.completed) {
        isLoading = false;
        isPlaying = false;
      } else if (state.processingState == ProcessingState.idle) {
        isLoading = false;
        isPlaying = false;
      }
      if (mounted) {
        setState(() {});
      }
    };
  }

  void checkAudioCanPlay({required Function onPlayAction}) {
    /// 在聊天页面中的问答消息播放语音需要校验语音是否还有效
    if (widget.source == CircleAudioPlayerSource.chatCard) {
      // TopicAnswerInfo.checkAudioCanPlay(answerId: answerId.toString(), onPlayAction: onPlayAction);
    } else {
      onPlayAction.call();
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          if (widget.cannotPlay) {
            Toast.showText('无法查看其他人的付费问答');
          } else {
            checkAudioCanPlay(onPlayAction: () {
              preparePlayAudio();
            });
          }
          widget.onCannotPlay?.call(widget.cannotPlay);
        },
        child: widget.source == CircleAudioPlayerSource.chatCard ||
                widget.source == CircleAudioPlayerSource.topicList ||
                widget.source == CircleAudioPlayerSource.userTopicList
            ? Container(
                height: 40.h,
                padding: const EdgeInsets.only(top: 8, bottom: 8, left: 8),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(6),
                    gradient: const LinearGradient(
                        colors: [Color(0xFFF7F7F7), Color(0xFFF7F7F7)],
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter)),
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      isPlaying
                          ? Image.asset('assets/app/home/play_voice_receive_black.gif',
                              width: 15, height: 15, fit: BoxFit.contain)
                          : Image.asset('assets/app/im/im_icon_voice_left3.png', width: 19, height: 19),
                      Text(isPlaying ? '${audioPlayingDuration}s″' : '${widget.audioDuration}s″',
                          style: TextStyle(fontSize: 14.sp, color: const Color(0xFF333333))),
                    ]),
              )
            : Container(
                color: Colors.transparent,
                width: 100,
                height: 30,
                alignment: Alignment.topRight,
                child: _playWidget()));
  }

  Widget _playWidget() {
    logs('home - player -   state = $isPlaying');

    if (isPlaying) {
      return Container(
          width: 24.w,
          height: 24.h,
          decoration: const BoxDecoration(
            image: DecorationImage(image: AssetImage('assets/app/home/home_img_vioce_bg.png')),
          ),
          padding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5),
          child: Image.asset('assets/app/home/play_voice_receive.gif', width: 10.w, height: 10.h, fit: BoxFit.contain));
    }
    if (isLoading) {
      return Container(
          width: 24.w,
          height: 24.h,
          decoration:
              const BoxDecoration(image: DecorationImage(image: AssetImage('assets/app/home/home_img_vioce_bg.png'))),
          padding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5),
          child: const CupertinoActivityIndicator(radius: 6));
    }
    return Image.asset('assets/app/home/home_img_vioce.png', width: 24.w, height: 24.h, fit: BoxFit.fill);
  }

  @override
  void didPushNext() {
    //打开其他页面之前停止播放
    super.didPushNext();
    _stopAudioPlay();
    isCurrentPage = false;
  }

  @override
  void didPop() {
    logs('---didPop');
    // 退出当前页面之前停止播放
    super.didPop();
    _stopAudioPlay();
    isCurrentPage = false;
  }

  @override
  void dispose() {
    super.dispose();
    IMKitRouter.instance.routeObserver.unsubscribe(this);
    WidgetsBinding.instance.removeObserver(this);
    _phoneStateSub?.cancel();
  }

  //处理来电话播放器停止播放的操作
  void _handlePhoneCall() async {
    _phoneStateSub?.cancel();
    bool havePermission = true;
    if (Platform.isAndroid) {
      PermissionStatus status = await Permission.phone.request();
      if (status == PermissionStatus.denied ||
          status == PermissionStatus.restricted ||
          status == PermissionStatus.limited ||
          status == PermissionStatus.permanentlyDenied) {
        havePermission = false;
      }
      if (status == PermissionStatus.granted) {
        havePermission = true;
      }
    }
    if (havePermission) {
      // _phoneStateSub = PhoneState.stream.listen((event) {
      //   JustAudioPlayer.instance.getCurrentPosition(
      //       onDurationChanged: (String playerId, bool playState, Duration duration) {
      //     if (playState) {
      //       _stopAudioPlay();
      //     }
      //   });
      // });
    }
  }
}
